package com.dmy.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dmy.chat.server.netty.ChannelManager;
import com.dmy.chat.server.netty.ChannelSender;
import com.dmy.chat.server.netty.message.Messages;
import com.dmy.common.entity.ResultBean;
import com.dmy.common.exception.ExinException;
import com.dmy.common.utils.CoderUtils;
import com.dmy.model.EUser;
import com.dmy.service.IUserService;
import com.dmy.vo.FriendListVo;
import com.dmy.vo.FriendRequestVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;


/**
 * create by huahuadelei for 2020/1/4
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @PostMapping("/login")
    public ResultBean login(@Validated @RequestBody EUser eUser, BindingResult bindingResult) {
        if(bindingResult.hasFieldErrors()){
            throw new ExinException("5401",bindingResult.getFieldError().getDefaultMessage());
        }
        EUser user = userService.login(eUser);
        user.setPassword(null);
        return ResultBean.success(user);
    }

    @PostMapping("/regist")
    public ResultBean regist(@Validated @RequestBody EUser eUser, BindingResult bindingResult, HttpSession session) {
        if(bindingResult.hasFieldErrors()){
            throw new ExinException("5401",bindingResult.getFieldError().getDefaultMessage());
        }
        String value = redisTemplate.boundValueOps("KAPTCHAPRODUCER_VILDCODE:" + session.getId()).get();
        if(!ObjectUtils.isEmpty(eUser.getValidaCode())&&!eUser.getValidaCode().equals(value)){
            throw new ExinException("6307","验证码错误");
        }
        userService.regist(eUser);
        return ResultBean.success();
    }

    @PostMapping("/updatePhoto")
    public ResultBean updatePhoto(@RequestBody EUser user){
        Assert.notNull(user,"parameter user not is a null");
        Assert.notNull(user.getId(),"用户ID不能为空");
        Assert.notNull(user.getPhotoDefault(),"用户图片地址不能为空");
        user.setPhotoBig(user.getPhotoDefault());
        userService.updateById(user);
        return ResultBean.success();
    }

    @GetMapping("/loadQR/{token}")
    public ResultBean loadUserQRCode(@PathVariable String token){
        byte[] bytes = userService.loadQr(token);
        String base64QrCode = CoderUtils.byteArrayToBase64String(bytes);
        return ResultBean.success(base64QrCode);
    }
    @GetMapping("/find/{userId}")
    public ResultBean findUserById(@PathVariable String userId){
         EUser user = userService.findUserById(userId);
        return ResultBean.success(user);
    }
    @PostMapping("/add_request/{token}")
    public ResultBean addUserRequest(@PathVariable String token, @RequestBody Map<String,String> param){
        String userId = param.get("userId");
        String type = param.get("r_type");
        userService.addUserRequest(token,userId,Integer.valueOf(type));
        return ResultBean.success();
    }
    @GetMapping("/getUserInfo/{token}")
    public ResultBean getUserInfo(@PathVariable String token){
        EUser user = userService.getUserInfo(token);
        return ResultBean.success(user);
    }
    @GetMapping("/queryUser/{username}")
    public ResultBean queryUser(@PathVariable String username){
        List<EUser> list = userService.list(new QueryWrapper<EUser>().like("username", username));
        return ResultBean.success(list);
    }
    @GetMapping("/queryFriendsRequest/{token}")
    public ResultBean queryFriendsRequest(@PathVariable String token){
        List<FriendRequestVo> requestVos = userService.queryFriendsRequest(token);
        return ResultBean.success(requestVos);
    }

    /**
     *  接受好友申请请求
     * @param token
     * @return
     */
    @PostMapping("/acceptReq/{token}")
    public ResultBean acceptReq(@PathVariable String token,@RequestBody Map<String,String> param){
        userService.acceptRequest(token,param.get("reqId"));
        return ResultBean.success();
    }

    /**
     *  接受好友申请请求
     * @param token
     * @return
     */
    @PostMapping("/ignore/{token}")
    public ResultBean agnoreReq(@PathVariable String token,@RequestBody Map<String,String> param){
        userService.agnoreReq(token,param.get("reqId"));
        return ResultBean.success();
    }

    @GetMapping("/friends/{token}")
    public ResultBean getFriendList(@PathVariable String token){
        Map<String, List<FriendListVo>> friends = userService.getFriends(token);
        return ResultBean.success(friends);
    }
    @GetMapping("/ws/send")
    public ResultBean send(@RequestParam String content){
        Messages messages = new Messages();
        messages.setContent(content);
        ((ChannelSender)ChannelManager.getInstance()).sendAll(messages);

        return ResultBean.success(messages);
    }
}
